let urlProtocol = 'ws://'
console.log(window.location)
if (window.location.protocol.includes('https')) {
  urlProtocol = 'wss://'
}
let wsInstance = null;
let socketUrl = null;
let connecting = false;
let sendCallback = null
const connctWebsocket = (socketParams) => {
  return new Promise((resolve, reject) => {
    if ('WebSocket' in window) {
      if (wsInstance) {
        resolve({ code: 0, msg: '已连接' })
        return;
      }
      let tmpSocketUrl = `${'wss://115292928app8001.downline.cn'}/websocket_4_openai?${socketParams}`;
      let tmpWsInstance = new WebSocket(tmpSocketUrl);

      //连接成功建立的回调方法
      tmpWsInstance.onopen = function () {
        console.log("WebSocket连接成功");
        wsInstance = tmpWsInstance;
        resolve(true)
      }
      tmpWsInstance.onerror = function (e) {
        console.log("WebSocket连接失败", e);
        // wsInstance = tmpWsInstance;
        // resolve(true)
        let err = { code: 500, errorMsg: "WebSocket连接失败", errorData: e }
        console.log(err)
        sendCallback && sendCallback(err)
        reject(err)
      }
      //连接关闭的回调方法
      tmpWsInstance.onclose = function () {
        console.log("WebSocket连接关闭");
        wsInstance=null;
      }
      tmpWsInstance.onmessage = function (event) {
        console.log("接收到数据",event,">>>>>>>>>>>>>>")
        sendCallback && sendCallback(event)
      }

    }
    else {
      let err = { code: 500, errorMsg: "浏览器不支持该功能" }
      console.log(err)
      reject(err)
    }
  })

}

export const sendWsData = (message,callback) => {
  console.log("开始发送数据", message)
  sendCallback=callback;
  wsInstance && wsInstance.send(message)
}

export const connect = (socketParams) => {
  return connctWebsocket(socketParams)
  return new Promise(async (resolve, reject) => {
    // let connectResult = await connctWebsocket(socketParams).catch((err) => {
    //   reject(err)
    // })
    // console.log('connectResult>>>>',connectResult)
    // if (connectResult) {
    //   resolve()
    // }
    // return;
    // else{
    //   reject();
    // }
  })
}
